<template>
  <div>
    <el-button size="small" icon="el-icon-download" @click="handleDownload">下载附件</el-button>
    <el-table class="form__inner_table"
              ref="attachments"
              border stripe
              :data="list || []"
              height="200">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="标题" prop="response.data.fileName[0]"></el-table-column>
    </el-table>

    <!--<el-pagination background :page-sizes="[10, 30, 50]"-->
    <!--@current-change="handleAttachmentsList"-->
    <!--:page-size="10"-->
    <!--layout="total, sizes, prev, pager, next"-->
    <!--:total="total">-->
    <!--</el-pagination>-->
  </div>
</template>

<script>
  import ajax from '@/utils/ajax'
  import {FILE_DOWNLOAD_PATH, FILE_BATCH_DOWNLOAD_PATH} from '@/config'
  import {download} from '../../../utils/download'

  export default {
    name: 'XdhFormAttachments',
    props: {
      list: {
        type: Array,
        default: []
      }
    },
    methods: {
      /**
       * 选择附件之后的操作，用于批量下载
       */
      handleDownload() {
        this.handleSelection('response.').then(({selections, selectionNames}) => {
          let fileId = selections[0]
          let fileName = selectionNames[0]
          const downloadFile = function (id, name) {
            const url = FILE_DOWNLOAD_PATH + 'fileSaveName=' + id + '&fileName=' + name
            download(url)
          }
          // 单个文件下载地址
          if (selections.length > 1) {
            ajax({
              method: 'post',
              url: FILE_BATCH_DOWNLOAD_PATH,
              data: {
                fileSaveName: selections
              }
            }).then(res => {
              fileName = fileId = res
              downloadFile(fileId, fileName)
            })
          } else {
            downloadFile(fileId, fileName)
          }
        })
      },
      handleSelection(key = 'pkValue') {
        const selection = this.$refs.attachments.selection;
        if (selection.length > 0) {
          return Promise.resolve({
            selections: selection.map(n => n.response.data.fileSaveName[0]),
            selectionNames: selection.map(n => n.response.data.fileName[0])
          });
        } else {
          this.$message({
            type: 'warning',
            message: '请至少勾选一条数据！'
          });
          return Promise.reject(selection);
        }
      }
    }
  }
</script>
